/**
 * This file is part of AppStoreBot.
 *
 *  AppStoreBot is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AppStoreBot is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AppStoreBot.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package lu.pragmaconsult.appstorebot.itunes;

import static lu.pragmaconsult.appstorebot.itunes.Constants.AJAX_NAME;
import static lu.pragmaconsult.appstorebot.itunes.Constants.ATT_VALUE;
import static lu.pragmaconsult.appstorebot.itunes.Constants.DATE_LIST_AVAILABLE_DAYS;
import static lu.pragmaconsult.appstorebot.itunes.Constants.DATE_LIST_AVAILABLE_WEEKS;
import static lu.pragmaconsult.appstorebot.itunes.Constants.SALES_URL;
import static lu.pragmaconsult.appstorebot.itunes.Constants.SELECT_NAME;
import static lu.pragmaconsult.appstorebot.itunes.Constants.VIEW_STATE;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import lu.pragmaconsult.appstorebot.BotContext;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;

/**
 * TODO: Type comment
 * 
 * @author Wilfried Vandenberghe (wilfried.vandenberghe at pragmaconsult.lu)
 */
class SelectDateBotState extends AbstractBotState {

	private static final Logger logger = LoggerFactory
			.getLogger(SelectDateBotState.class);

	private boolean reportAvailable = true;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * lu.pragmaconsult.appstorebot.itunes.AbstractBotState#createHttpMethod
	 * (lu.pragmaconsult.appstorebot.BotContext,
	 * org.apache.commons.httpclient.HttpClient)
	 */
	@Override
	protected HttpMethod createHttpMethod(BotContext context,
			HttpClient httpClient) {
		List<String> availableDateReport = null;
		if(context.isWeekly()) {
			availableDateReport = Arrays.asList(context
					.getContextAttribute(DATE_LIST_AVAILABLE_WEEKS).split(","));
		} else {
			availableDateReport = Arrays.asList(context
				.getContextAttribute(DATE_LIST_AVAILABLE_DAYS).split(","));
		}

		// check if the report is available
		String reportDates = context.getContextAttribute("reportDates");
		int index = Integer.parseInt(context.getContextAttribute("reportDatesIndex"));

		String dateStr = reportDates.split(",")[index];
		if (availableDateReport.contains(dateStr)) {
			if (context.isVerbose()) {
				logger.info("Downloading report for: " + dateStr);
			}
			PostMethod method = new PostMethod(SALES_URL);

			NameValuePair ajaxRequest = new NameValuePair("AJAXREQUEST", context.getContextAttribute(AJAX_NAME));
			NameValuePair theForm = new NameValuePair("theForm", "theForm");
			NameValuePair theFormNotNormal = new NameValuePair("theForm:xyz", "notnormal");
			NameValuePair theFormVendorType = new NameValuePair("theForm:vendorType", "Y");
			
			NameValuePair dateDay1, dateDay2, dateDay3 = null;
			if(context.isWeekly()) {
				dateDay1 = new NameValuePair("theForm:datePickerSourceSelectElementSales", context.getContextAttribute(DATE_LIST_AVAILABLE_DAYS).split(",")[0]);
				dateDay2 = new NameValuePair("theForm:weekPickerSourceSelectElement", dateStr);
				dateDay3 = new NameValuePair("theForm:weekPickerSourceSelectElement", dateStr);
			} else {
				dateDay1 = new NameValuePair("theForm:datePickerSourceSelectElementSales", dateStr);
				dateDay2 = new NameValuePair("theForm:datePickerSourceSelectElementSales", dateStr);
				dateDay3 = new NameValuePair("theForm:weekPickerSourceSelectElement", context.getContextAttribute(DATE_LIST_AVAILABLE_WEEKS).split(",")[0]);
			}
			NameValuePair viewState = new NameValuePair("javax.faces.ViewState", context.getContextAttribute(VIEW_STATE));
			NameValuePair select = new NameValuePair(context.getContextAttribute(SELECT_NAME), context.getContextAttribute(SELECT_NAME));
			method.setRequestBody(new NameValuePair[] { ajaxRequest, theForm,
					theFormNotNormal, theFormVendorType, dateDay1, dateDay2,
					dateDay3, viewState, select });

			return method;
		} else {
			logger.info("Report is not available for date: " + dateStr);
			context.setContextAttribute("reportDatesIndex", Integer.toString(index++));
			reportAvailable = false;
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see lu.pragmaconsult.appstorebot.itunes.AbstractBotState#getNextState()
	 */
	@Override
	protected BotState getNextState() {
		if (reportAvailable) {
			return new DownloadReportBotState();
		} else {
			return new SelectDateBotState();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * lu.pragmaconsult.appstorebot.itunes.AbstractBotState#processResponseBody
	 * (lu.pragmaconsult.appstorebot.BotContext,
	 * org.apache.commons.httpclient.HttpMethod)
	 */
	@Override
	protected void processResponseBody(BotContext context, HttpMethod method) {
		HtmlParser parser;
		try {
			parser = new HtmlParser(method.getResponseBodyAsStream());

			// TODO: replace following by XPath expression
			Node node = parser.getDocument().getChildNodes().item(0)
					.getChildNodes().item(1).getChildNodes().item(6)
					.getChildNodes().item(1).getAttributes().getNamedItem(
							ATT_VALUE);
			context.setContextAttribute(VIEW_STATE, node.getNodeValue());
		} catch (IOException e) {
			throw new IllegalStateException(e);
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}
	
	/**
	 * Only for test purpose
	 * @return
	 */
	boolean isReportAvailable() {
		return reportAvailable;
	}

}
